package com.java.escape.computeAndListOrInterface;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName ObjectListEqualsError
 * @Description 对象的 equals方法和hashcode 问题
 * @Author wyp
 * @Date 2023/8/24 15:41
 * @Version 1.0
 */
public class ObjectListEqualsError {

    private static class Cat {
        private String name;
        private String age;

        public Cat() {
        }

        public Cat(String name, String age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Cat cat = (Cat) o;

            if (!name.equals(cat.name)) return false;
            return age.equals(cat.age);
        }

        @Override
        public int hashCode() {
            int result = name.hashCode();
            result = 31 * result + age.hashCode();
            return result;
        }
    }

    public static void main(String[] args) {
        //1.要使对象在逻辑上相等，需要重写equals方法
        Cat cat = new Cat("xxx", "18");
        Cat cat1 = new Cat("xxx", "18");
        System.out.println(cat.equals(cat1));
        //2.在集合中的特殊性，需要重写hashcode
        Set<Cat> cats = new HashSet<>();
        Cat cat2 = new Cat("aa", "22");
        Cat cat3 = new Cat("aa", "22");
        cats.add(cat2);
        cats.add(cat3);
        System.out.println(cats.size());

        HashMap<Cat, Integer> hashMap = new HashMap<>();
        hashMap.put(cat2, 1);
        hashMap.put(cat3, 1);
        System.out.println(hashMap.size());
    }
}
